package org.dval.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author duai
 * @version V1.0
 * @Title: Excel
 * @Package org.dval.core
 * @Description: 注解导入
 * @date 2017-12-14 15:10
 */
public class ImportExcelAnnKit {
    public static <T> List<T> getImportData(File file, Class<T> clazz) {
        try {
            return getImportData(new FileInputStream(file), clazz, file.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Collections.emptyList();
    }

    public static <T> List<T> getImportData(InputStream file, Class<T> clazz, String fileName) {
        List<T> result = new LinkedList<>();
        try {
            List<Map<String, Object>> datas = ImportExcelKit.getData(file, fileName);
            Map<Field, ExcelField> fields = Arrays.stream(clazz.getDeclaredFields())
                    .filter(item -> item.getDeclaredAnnotation(ExcelField.class) != null)
                    .collect(Collectors.toMap(item -> item, item -> item.getDeclaredAnnotation(ExcelField.class)));

            for (Map<String, Object> bean : datas) {
                Object object = clazz.newInstance();
                fields.forEach((key, value) -> {
                    key.setAccessible(true);
                    try {
                        Object data = ImportExcelKit.getData(bean.get(value.headName()), key.getType());
                        if (data == null) {
                            return;
                        }
                        key.setAccessible(true);
                        if (data instanceof Boolean) {
                            if (key.getType() != Boolean.class) {
                                key.set(object, ((Boolean)data) ? 1 : 0);
                                return;
                            }
                        }
                        key.set(object, data);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                });
                result.add((T) object);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
